<?php namespace App\Core\Repository;

use App\Core\Repository\Repository;
use App\Core\Exceptions\RuntimeError;

abstract class Criteria {
    
    protected $name = '';
    protected $model;
    protected $query;
    protected $booted = false;
    protected $global = false;

    /**
     * @param $model
     * @param Repository $repository
     * @return mixed
     */
    public function apply(Repository $repository){
        $this->boot($repository);
        if(!$this->validate()){
            throw new RuntimeError();
        }
    }
    
    public function getName(){
        return $this->name ? $this->name : static::class;
    }
    
    public function setName($name){
        $this->name = $name;
        return $this;
    }
    
    public function isGlobal(){
        return $this->global;
    }
    
    public function enGlobal(){
        $this->global = true;
        return $this;
    }
    
    public function disGlobal(){
        $this->global = false;
        return $this;
    }
    
    protected function boot(Repository $repository){
        $this->model = $this->getModelFromRepository($repository);
        $this->query = $this->getQueryFromRepository($repository);
        $this->booted = true;
        return $this;
    }
    
    protected function getModelFromRepository(Repository $repository){
        return $repository->getModel();
    }
    
    protected function getQueryFromRepository(Repository $repository){
        return $repository->getQuery();
    }
    
    protected function formatField($model, $fieldRaw){
        if(strpos($fieldRaw, '.') === false){
            return $model->getTable().'.'.$fieldRaw;
        }else{
            return $fieldRaw;
        }
    }
    
    protected function validate(){
        return $this->booted;
    }
}